import { useApiInterceptor } from '@/utils/composition/useApiInterceptor'
import { request, type ApiInterceptor, type RequestConfig } from '@/utils/request'
import {
  ConnectionFailed,
  ErrorNoticeQueryKeys,
  LockedByLocalControl,
  ProgramNotWritable,
  RemoteControlNotActive,
  RemoteStartNotActive,
  WrongOperationState,
} from '@/constants/ErrorNoticeActions'
import { useApplianceStore } from '@/store/appliance'
import store from '@/store'
import { DOOR_STATE_OPEN, POWER_STATES } from '@/constants/Command'
import { getControllerContext } from '../context'
import {
  confirmPowerOn,
  confirmToControlLevelTips,
  showChildLockEnabledModal,
  showDoorOpenedRemoteStartDisabledModal,
  showErrorNativeModal,
  showFrequentlyOperationModal,
  showLocalOperatingModal,
  triggerNoticeQuery,
} from './errorNotice'
import errorList from '@/constants/Errors'
import { toHome } from '@/utils/mpHelper'

export type ErrorData = {
  key: string
  description: string
}

/**
 * 报错顺序：
 *  - 报错1：家电离线
 *  - 报错2：远程操作未打开
 *  - 报错3：家电被本地控制
 *  - 报错4：家电关机
 *  - 报错5：家电远程启动未打开
 *  - 报错6：洗衣机、洗碗机门未关
 *  - 报错7：未选中程序
 *  - 报错8：选中程序不支持预约启动
 */
async function handleErrorInterceptor(errorData: ErrorData, requestConfig: RequestConfig): Promise<boolean> {
  const { key: errorKey } = errorData

  const applianceStore = useApplianceStore(store)
  const currentController = getControllerContext(applianceStore.currentHaId)

  // 无当前家电 不拦截请求
  if (!currentController) return false

  // 当前家电属性
  const controllerStore = currentController.store

  // 远程操作未打开 SMM洗碗机特殊处理
  if (errorKey === RemoteControlNotActive) {
    if (controllerStore.showControlLevelTipsOnRemoteControlError) {
      confirmToControlLevelTips(controllerStore._datasource)
      // 拦截后续错误处理
      return true
    }
  }

  // 家电被本地控制
  if (errorKey === LockedByLocalControl) {
    showLocalOperatingModal()
    // 拦截后续错误处理
    return true
  }

  // 关机报错
  if (errorKey === WrongOperationState && controllerStore.powerState !== POWER_STATES.ON) {
    confirmPowerOn(currentController).then(() => request(requestConfig))
    return true
  }

  /**
   * 离线报错时 判断家电连接状态
   *  - 在线状态下 特殊处理：弹出提示 操作频繁
   */
  if (errorKey === ConnectionFailed && controllerStore.isOffline !== true) {
    showFrequentlyOperationModal()
    // 拦截后续错误处理
    return true
  }

  // 远程启动未开启 判断门是否打开
  if (errorKey === RemoteStartNotActive) {
    const isDoorOpened = controllerStore.doorState === DOOR_STATE_OPEN
    // 门打开 特殊处理 弹出提示 (不使用Action Info的弹框)
    if (isDoorOpened) {
      showDoorOpenedRemoteStartDisabledModal()
      // 拦截后续错误处理
      return true
    }
  }

  // 报错程序无法写入 且 童锁已打开
  if (errorKey === ProgramNotWritable && controllerStore.childLockOn === true) {
    showChildLockEnabledModal()
    // 拦截后续错误处理
    return true
  }

  // 报错errorKey特殊处理
  controllerStore.specialErrorInterceptor(errorData, requestConfig)

  const noticeQuery = ErrorNoticeQueryKeys[errorKey]
  // 找不到通知配置 不拦截请求
  if (!noticeQuery) return false

  // 获取接口返回的通知配置
  return triggerNoticeQuery(noticeQuery)
}

const errorNoticeInterceptor: ApiInterceptor<ErrorData> = async (res, response, requestConfig) => {
  if (res.code === 409 && res.data?.key) {
    const shouldIntercept = await handleErrorInterceptor(res.data, requestConfig)
    return shouldIntercept
  }

  // 家电被移除分享 返回首页
  if (res.code === 10015) {
    const errorItem = errorList.find((error) => error.code === res.code)
    if (!errorItem) return false

    showErrorNativeModal({
      content: errorItem.promptText,
    }).then(() => toHome())
    return true
  }
}

export function useErrorNotice() {
  useApiInterceptor(errorNoticeInterceptor)
}
